var zip = "16801";

function initialize(useWebServices, zipCode) {
	
	if (zipCode === null) {
		zipCode = "16801";
	}
	
	if (useWebServices) {
		getPostsByZip(zipCode);
	}
	else {
		var category = new Array();
		category[0] = "restaurant";
		//category[1] = "classified";
		//category[2] = "restaurant";
		//category[3] = "restaurant";
		
		var title = new Array();
		title[0] = "State College Happy Hour Special";
		//title[1] = "Bicycle For Sale";
		//title[2] = "State College Creamery";
		//title[3] = "Allen Street Grill Special";
		
		var image = new Array();
		image[0] = "./images/happyhour.jpg";
		//image[1] = "./images/bicycle-image.jpg";
		//image[2] = "./images/psu_ice_cream.jpg";
		//image[3] = "./images/allen.jpg";
		
		var description = new Array();
		description[0] = "Drink Specials, Live Band @ 5pm!";
		//description[1] = "Bicycle for Sale on Allen Street, asking price $50 but will to negogiate.  Contact seller@gmail.com or 555-123-4567.";
		//description[2] = "Looking for Ice Cream?  Visit the State College Creamery located by East Halls!";
		//description[3] = "Steak Special Tonight!  $25 for New York Steak!";
		
		appendPosts(category, title, image, description);
	}							 
}

function getPostsByZip(zip) {
	var xmlText = loadXMLDocAsText("./svhost/Service1.svc/GetUserPostByZip?zip=" + zip);
	var xmlDoc = loadXMLStringToDoc(xmlText);
	parseResponse(xmlDoc);

}

function parseResponse(xmlDoc) {
	try {
		var categories = new Array();
		var titles = new Array();
		var images = new Array();
		var descriptions = new Array();
		var imageWidths = new Array();
		var postIds = new Array();
		var popularity = new Array();
		
		var numOfPosts = xmlDoc.getElementsByTagName("UserPosts")[0].childNodes.length;
		
		for (i=0; i < numOfPosts; i++) {
			postIds.push(xmlDoc.getElementsByTagName("Id")[i].childNodes[0].nodeValue);
			categories.push(xmlDoc.getElementsByTagName("CategoryTitle")[i].childNodes[0].nodeValue);
			titles.push(xmlDoc.getElementsByTagName("Title")[i].childNodes[0].nodeValue);
			
			var img = xmlDoc.getElementsByTagName("ImgURL")[i].childNodes[0].nodeValue;
			if (typeof img == 'undefined') {
				img = "http://bportlibrary.org/main/uploads/bulletin-board.jpg";
			}
			
			images.push(xmlDoc.getElementsByTagName("ImgURL")[i].childNodes[0].nodeValue);
			descriptions.push(xmlDoc.getElementsByTagName("Description")[i].childNodes[0].nodeValue);
			popularity.push(xmlDoc.getElementsByTagName("Popularity")[i].childNodes[0].nodeValue);
			imageWidths.push("250");
		}
		appendPosts(categories, titles, images, descriptions, imageWidths, "false", postIds, popularity);
		return true;
	}
	catch(e){
		console.log(e);
		return false;
	}
}

function appendPosts(categories, titles, images, descriptions, imageWidths, thirdParty, postIds, popularity) {	
	for (i=0; i < categories.length; i++) {		
		var finalString = titles[i].replace(/[^a-zA-Z 0-9]+/g,'');
		stringTitle = "'" + finalString + "'";		
		var stringImage = "'" + images[i] + "'";
		
		var desc = descriptions[i];
		var desc_replace = desc.replace('&amp;#39;', "");
		if (desc_replace.indexOf("'") != -1) {
			desc_replace = "";
		}
		
		var stringDescription = "'" + desc_replace + "'";
		var postId = postIds[i];
		
			
		if (thirdParty === "true") {
			stringPopup = i;
		}
		else {
			stringPopup = stringDescription;
		}
		
		var appendString = '<div class="box ' + categories[i] + '">' +
								'<h2 class="box-title">' + titles[i] + '</h2>' +
								'<div style="text-align: center;" class="box-text">' +
									'<a href="javascript:popupDialog(' + stringTitle + ',' + stringImage + ',' + stringPopup + ',' + postId + ',' + popularity[i]+ ')"><img src="' + images[i] + '" width="' + imageWidths[i] + '" /></a>' +
								'</div>';
		
		var rating = Math.round(popularity[i]);
		var imagelink = "./img/stars-10-0.gif";
		
		if (rating === 1) {
			imagelink = "./img/stars-10-1.gif";
		}
		else if (rating === 2) {
			imagelink = "./img/stars-10-2.gif";
		}
		else if (rating === 3) {
			imagelink = "./img/stars-10-3.gif";
		}
		else if (rating === 4) {
			imagelink = "./img/stars-10-4.gif";
		}
		else if (rating === 5) {
			imagelink = "./img/stars-10-5.gif";
		}
		else if (rating === 6) {
			imagelink = "./img/stars-10-6.gif";
		}
		else if (rating === 7) {
			imagelink = "./img/stars-10-7.gif";
		}
		else if (rating === 8) {
			imagelink = "./img/stars-10-8.gif";
		}
		else if (rating === 9) {
			imagelink = "./img/stars-10-9.gif";
		}
		else if (rating === 10) {
			imagelink = "./img/stars-10-10.gif";
		}
		
		var popularityString =	'<div style="text-align: left;" class="box-text">' +
									descriptions[i] + '<br>' +
									'Popularity: ' +
									'<img src="' + imagelink + '">' +
								'</div>' +
							'</div>';
		
		appendString += popularityString;
		
		$('.inner').append(appendString);
	}
	 
	return true;
}

function loadXMLDocAsText(url) {
    var xhttp = createXHR();
    xhttp.open("GET", url, false);
    xhttp.send(null);

    // unable to get a real XML document from IE, so this and
    // on return, additional logic for IE
    return xhttp.responseText;
}

function createXHR() {
    try { return new XMLHttpRequest(); } catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
    alert("XMLHttpRequest not supported");
    return null;
}

function loadXMLStringToDoc(text) {	
	if (window.DOMParser)
	  {
	  parser=new DOMParser();
	  xmlDoc=parser.parseFromString(text,"text/xml");
	  }
	else // Internet Explorer
	  {
	  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	  xmlDoc.async=false;
	  xmlDoc.loadXML(text);
	  }
	
	return xmlDoc;
}

function setStorageKey(id) {	
	sessionStorage.setItem('zip', id);
}

function getStorageKey(id) {	
	return sessionStorage.getItem(id);
}

function filter() {
	var $container = $('#content');
	$container.isotope({
		filter: '*',
		animationOptions: {
	     duration: 250,
	     easing: 'linear',
	     queue: false
	   }
	});
	
	$('#nav a').click(function(){
	  var selector = $(this).attr('data-filter');
	    $container.isotope({ 
		filter: selector,
		animationOptions: {
	     duration: 250,
	     easing: 'linear',
	     queue: false			 
	   }
	  });
	  return false;
	});	
	
	setInterval(function(){filter()},50);
	
	function filter(selection) {
		var $container = $('#content');
		$container.isotope({
			filter: selection,
			animationOptions: {
		     duration: 250,
		     easing: 'linear',
		     queue: false
		   }
		});
	}		
}

function popupDialog(title, imageUrl, description, postId, rating) {
    
    $( "#dialog" ).dialog( "open" );   
    $('.hello').remove();
    $('.hello2').remove();
    $('.hello3').remove();
    $('.hello4').remove();
    $('.hello5').remove();
    
    if (typeof description == "number") {
    	
    	var yelpDescription = "Rating: " + globalData.businesses[description].rating + "<br>" + "<br>" + 
    						  globalData.businesses[description].snippet_text  + "<br>" + "<br>" +
    						  "Phone: " + globalData.businesses[description].phone  + "<br>" + "<br>" +
    						  "Address: " + globalData.businesses[description].location.display_address  + "<br>" + "<br>" +
    						  "<a href='" + globalData.businesses[description].url + "'>" + globalData.businesses[description].url + "</a>";
    	
	    var detailsString = '<div style="text-align: center;" class="hello"><h3>' + title + '</h3>' + 
							'<div style="text-align: center;">' +
									'<img src="' + imageUrl + '" style="padding:10px;" /></a>' +
								'</div>' +
							'<div style="text-align: center;">' +
								yelpDescription +
							'</div><br>' + 
							'</div>';
    }
    else {
	    var detailsString = '<div style="text-align: center;" class="hello"><h3>' + title + '</h3>' + 
											'<div style="text-align: center;">' +
											'<img src="' + imageUrl + '" style="padding:10px;" /></a>' +
										'</div>' +
								'<div style="text-align: center;">' +
									description +
								'</div><br>' + 
							'</div>';
    }
    $('.inner2').append(detailsString);
        
    
    var commentsString = '<div style="text-align: center;" class="hello2">' +
    							'<input type="text" id="commentTextBox" name="commentTextBox" size="60">' +
    							'<button onclick="createComments(' + postId + ')">Comment</button>' +
    						'</div>';
    
    $('.inner2').append(commentsString);
    
    var sessionid = sessionStorage.getItem("sessionid");
    if (sessionid) { 
	    var thumps = '<div style="text-align: center;" class="hello4">Rate: Mesh Up <a href="javascript:rateUp(' + postId + ')"><img src="./img/thumbs_up.png" alt="Thumbs Up" width="32" height="32"></a>' +
	    				'     Mesh Down <a href="javascript:rateDown(' + postId + ')"><img src="./img/thumbs_down.png" alt="Thumbs Down" width="32" height="32"></a>' +
	    				'<br></div>';
	    $('.inner2').append(thumps);				
    }
    else {
    	var other = '<div style="text-align: center;" class="hello5">Rate: Please Login to Rate!<br></div>';
    	$('.inner2').append(other);
    }
    
    
    getComments(postId);
    
       
}

function addComments(comments) {
	if (comments != null) {
	    var commentsDiv = '<div class="hello3"><br />' + 
					'<p>' + comments + '</p>' +
				'</div>';
	
	    $('.inner2').append(commentsDiv);
	    return true;
	}
	else {
		return false;
	}
}


